<?php
// +----------------------------------------------------------------------
// | module: 会议管理
// +----------------------------------------------------------------------
// | Author: 小西瓜 <751707632@qq.com>
// +----------------------------------------------------------------------
namespace app\api\controller;

use cmf\controller\BaseController;
use app\api\controller\Common;
use think\Db;
use think\Validate;
use app\api\model\ImsAddressModel;
use app\api\model\PortalCategoryModel;
use app\api\model\ImsMeetingLiveModel;
use app\api\model\ImsMeetingJoinModel;
use app\api\model\SlideItemModel;

class MeetingController extends CommonController
{

	/**
	 * 会议展厅
	 */
	public function meetingRoom()
	{
		$param = request()->param(); // 获取用户传参
		// 检查登录
		if ( !isset($param['token_key']) || empty($param['token_key'])) {
			return returnJson(400, 'token_key不能为空');
		} else {
			$verifyToken = $this->verifyToken($param['token_key']);
			if ( $verifyToken != '1111') return $verifyToken;
		}
		$this->traceLog('请求了[会议展厅]接口'); // 操作日志
		// 获取会议展厅banner
		$slideModel = new SlideItemModel();
		$banner  = $slideModel->show(3);
		// 获取会议分类
		$categoryModel = new PortalCategoryModel();
		$category = $categoryModel->categoryTree(2,1,'id,name');
		// 查询可以查看的会议
		$meetingLiveModel = new ImsMeetingLiveModel();
		$where['vm.is_detele'] = 0; // 未删除
		$where['vm.status'] = 5; // 已完成
		$where['vm.is_open'] = 1; // 公开的
		foreach ( $category as $key => $val ) {
			$where['vm.type_id'] = $val['id'];
			$category[$key]['data'] = $meetingLiveModel->MeetingList($where, 1, 2);
			if ( $category[$key]['data']['count'] == 0 ) {
				unset($category[$key]); // 删除没有数据分类
			} 
		}

		return returnJson(200, '', ['banner'=>$banner, 'category'=>$category]);
	}

	/**
	 * 会议列表-分支
	 */
	public function meetingListBranch()
	{
		$param = request()->param(); // 获取用户传参
		// 检查登录
		if ( !isset($param['token_key']) || empty($param['token_key'])) {
			return returnJson(400, 'token_key不能为空');
		} else {
			$verifyToken = $this->verifyToken($param['token_key']);
			if ( $verifyToken != '1111') return $verifyToken;
		}
		$this->traceLog('请求了[会议列表-分支]接口'); // 操作日志

		if ( isset($param['page']) && !empty($param['page']) ) $this->page = $param['page'];
		if ( isset($param['limit']) && !empty($param['limit']) ) $this->limit = $param['limit'];
		if ( isset($param['keyword']) && !empty($param['keyword']) ) {
			$where['vm.vm_title'] = ['like', '%'.$param['keyword'].'%']; // 标题查询
		}
		if ( isset($param['start_time']) && !empty($param['start_time']) && isset($param['end_time']) && !empty($param['end_time']) ) {
            $where['vm.start_time'] = ['between',[$param['start_time'],$param['end_time']]]; // 时间区间
        }
		if ( isset($param['type_id']) && !empty($param['type_id']) ) {
			// 获取会议展厅banner
			$slideModel = new SlideItemModel();
			if ( $param['type_id'] == 'example' ) {
				$banner  = $slideModel->show(4);
				$where['vm.labels'] = 1; // 示范案例
			} elseif ( $param['type_id'] == 'excellent' ) {
				$banner  = $slideModel->show(5);
				$where['vm.labels'] = 2; // 优秀案例
			} else {
				$where['vm.type_id'] = $param['type_id']; // 普通分类
				$category = Db::name('portal_category')->where('id', $param['type_id'])->value('more');
				$category = json_decode($category);
				$banner['image'] = cmf_get_image_url(str_replace("\\","/",$category->thumbnail)); // 处理图片
			}
		}

		//查询会议列表
		$meetingLiveModel = new ImsMeetingLiveModel();
		$where['vm.is_detele'] = 0; // 未删除
		$where['vm.status'] = 5; // 已完成
		$where['vm.is_open'] = 1; // 公开的
		$meetingList = $meetingLiveModel->MeetingList($where, $this->page, $this->limit);

		return returnJson(200, '', ['banner'=>$banner, 'data'=>$meetingList]);
	}

	/**
	 * 我的会议列表查询
	 */
	public function myMeetingList()
	{
		$param = request()->param(); // 获取用户传参

		// $this->traceLog('请求了[我的会议列表查询]接口'); // 操作日志
		// 数据验证
		$rule = [
			'token_key' => 'require',
			'my_msg'	=> 'require|in:1,2,3',
			'vm_status'	=> 'in:1,2',
			'page'	=> 'number',
			'limit' 	=> 'number',
			'join_status' => 'in:1,2,3,4,5'
        ];
        $validate = new Validate($rule);
        if(!$validate->check($param)){
            return returnJson(400, $validate->getError());
        }
        // 检查登录
		$verifyToken = $this->verifyToken($param['token_key']);
		if ( $verifyToken != '1111') return $verifyToken;

		if ( isset($param['vm_status']) ) {
			if ( $param['vm_status'] == 1 ) {
		        $where['vm.status'] = ['not in','3,5']; // 排除审核未通过的、已完成
			} elseif ( $param['vm_status'] == 2 ) {
				$where['vm.status'] = ['in','5']; // 查询已完成的会议
			}
		}
		if ( isset($param['page']) && !empty($param['page']) ) $this->page = $param['page'];
		if ( isset($param['limit']) && !empty($param['limit']) ) $this->limit = $param['limit'];
		if ( isset($param['keyword']) && !empty($param['keyword']) ) {
			$where['vm.vm_title'] = ['like', '%'.$param['keyword'].'%']; // 标题查询
		}
		if ( isset($param['category_id']) && !empty($param['category_id']) ) {
			$where['pc.id'] = $param['category_id']; // 分类查询
		}
		if ( isset($param['start_time']) && !empty($param['start_time']) && isset($param['end_time']) && !empty($param['end_time']) ) {
            $where['vm.start_time'] = ['between',[$param['start_time'],$param['end_time']]]; // 时间区间
        }

        $where['vm.is_detele'] = 0; // 排除已删除的
        if ( $param['my_msg'] == 1 )  {
			$where['mj.join_id'] = $this->user_id; // 我需要参加的
			// 获取会议列表
			$joinModel = new ImsMeetingJoinModel();
			$joinList = $joinModel->myMeetingList($where, $this->page, $this->limit);

			return returnJson(200, 'myMeetingList', $joinList);
        } elseif ( $param['my_msg'] == 2 ) {
        	$where['vm.user_id'] = $this->user_id; // 我发起的
        } elseif ( $param['my_msg'] == 3 ) {
        	$where['vm.compere_id'] = $this->user_id; // 我主持的
        }

        // 获取会议列表
        $meetingModel = new ImsMeetingLiveModel();
        $meetingList = $meetingModel->myMeetingList($where, $this->page, $this->limit);
		return returnJson(200, 'myMeetingList', $meetingList);

	}

	/**
	 * 会议查询（条件接口）
	 */
	public function meetingQueryCondition()
	{
		$data['status'] = meetingJoinStatus(); // 参会状态
		// 获取会议分类
		$categoryModel = new PortalCategoryModel();
		$category = $categoryModel->categoryTree(2,1, 'id,name');
		$data['category'] = $category; // 会议类型

		return returnJson(200, '', $data);
	}

	// ------------------------------------------------------------------------

	/**
	 * 会议详情-未开始
	 */
	public function meetingDateilsFuture()
	{
		$param = request()->param(); // 获取用户传参
		// 检查登录
		if ( !isset($param['token_key']) || empty($param['token_key'])) {
			return returnJson(400, 'token_key不能为空');
		} else {
			$verifyToken = $this->verifyToken($param['token_key']);
			if ( $verifyToken != '1111') return $verifyToken;
		}
		$this->traceLog('请求了[会议详情-未开始]接口'); // 操作日志

		if ( !isset($param['vm_id']) || empty($param['vm_id']) ) return json(['code' => 400, 'msg' => '缺少参数']);
		if (!(Db::name('ims_meeting_live')->where('id', $param['vm_id'])->find())) return json(['code' => 400, 'msg' => '没有会议资料']);

		// 查询会议详情
        $meetingModel = new ImsMeetingLiveModel();
        $meetingInfo = $meetingModel->meetingDateilsFuture(['vm.id'=>$param['vm_id']]);
        // 根据用户ID判断是不是会议主持者
        if ( $this->user_id == $meetingInfo['id'] ) {
        	// 生成推流地址
        	$push = pushDomain();
        	$meetingInfo['push_domain']['rtmp'] = 'rtmp://'.$this->PrivateKeyA($push['domain'], '', $push['key'], '/meeting/'.$meetingInfo['id']);
        } else {
        	// 生成播流地址
        	$pull = pullDomain();
        	$meetingInfo['pull_domain']['rtmp'] = 'rtmp://'.$this->PrivateKeyA($pull['domain'], '', $pull['key'], '/meeting/'.$meetingInfo['id']);
        	$meetingInfo['pull_domain']['flv'] = 'http://'.$this->PrivateKeyA($pull['domain'], '',  $pull['key'], '/meeting/'.$meetingInfo['id'].'.flv');
        	$meetingInfo['pull_domain']['m3u8'] = 'http://'.$this->PrivateKeyA($pull['domain'], '', $pull['key'], '/meeting/'.$meetingInfo['id'].'m3u8');
        }

		return returnJson(200, '', $meetingInfo);
	}

	/**
	 * 会议回放
	 */
	public function meetingPlayback()
	{
		$param = request()->param(); // 获取用户传参
		// 检查登录
		if ( !isset($param['token_key']) || empty($param['token_key'])) {
			return returnJson(400, 'token_key不能为空');
		} else {
			$verifyToken = $this->verifyToken($param['token_key']);
			if ( $verifyToken != '1111') return $verifyToken;
		}
		$this->traceLog('请求了[会议回放]接口'); // 操作日志

		if ( !isset($param['vm_id']) || empty($param['vm_id']) ) return json(['code' => 400, 'msg' => '缺少参数']);
		if (!(Db::name('ims_meeting_live')->where('id', $param['vm_id'])->find())) return json(['code' => 400, 'msg' => '没有会议资料']);

		// 查询会议详情
        $meetingModel = new ImsMeetingLiveModel();
        $meetingInfo = $meetingModel->meetingPlayback(['vm.id'=>$param['vm_id']]);

		return returnJson(200, '', $meetingInfo);
	}
	
	// ---------------------------------------------------------------------

	/**
	 * 发起会议
	 */
	public function meetingApply()
	{
		if ( request()->isPost() ) {
			$param = request()->param(); // 获取用户传参
			// 数据验证
			$rule = [
				'token_key' => 'require',
                'vm_title' 	=> 'require|chsDash',
                'type_id'	=> 'require|number',
                'join_way'	=> 'require|in:1,2,3',
                'join_address_id'	=> 'number',
                'compere_id'	=> 'require',
                'start_time'	=> 'require|date',
                'duration'	=> 'require|number',
                'join_uid_all'	=> 'require',
            ];
            $validate = new Validate($rule);
            if(!$validate->check($param)){
                return returnJson(400, $validate->getError());
            }
			// 检查登录
			$verifyToken = $this->verifyToken($param['token_key']);
			if ( $verifyToken != '1111') return $verifyToken;
			// 职务权限验证
			$verifyDuty = $this->verifyDuty('meeting');
			if ( $verifyDuty != '1111') return $verifyDuty;
			// 检查标题名防止重复
			if ( Db::name('ims_meeting_live')->where('vm_title',$param['vm_title'])->find() ) {
				return returnJson(400, '主题已被使用，请更换');
			}

			$data['user_id'] 	= $this->user_id;
			$data['vm_title'] 	= htmlentities(trim($param['vm_title']));
			$data['type_id']	= htmlentities($param['type_id']);
			$data['start_time']		= htmlentities($param['start_time']);
			$data['duration']		= htmlentities($param['duration']);
			$data['join_way']		= htmlentities($param['join_way']);

			// 检查分类ID
			if ( !(Db::name('portal_category')->where('id',$data['type_id'])->value('id')) ) return returnJson(400, '分类ID不存在');

			// 检查参加会议方式
			if ( in_array($data['join_way'], [1,3]) ) {
				if ( !isset($param['join_address_id']) || empty($param['join_address_id']) ) return returnJson(400, '现场地址不能为空');
				$data['join_address_id'] = htmlentities($param['join_address_id']);
				// 检查地址
				if ( !(Db::name('ims_address')->where('id',$data['join_address_id'])->value('id')) ) return returnJson(400, '现场地址ID不存在');
			}

			$data['compere_id']	= $this->userInfoOne($param['compere_id']); // 获取主持人最新信息
			if ( isset($param['compere_id']) && (empty($data['compere_id']) || $data['compere_id'] == 0) ) return returnJson(400, '主持人不存在');
			$data['compere_name'] = Db::name('ims_member')->where('id',$data['compere_id'])->value('staff_name');

			// 检查开始时间
			if ( $data['start_time'] < date("Y-m-d H:i:s", time()) ) return returnJson(400, '开始时间不能晚于当前时间');

			// 处理图片
			$file = request()->file('covar_pic'); // 获取图片对象
		    if($file){
		        $info = $file->validate(['size'=>1567800,'ext'=>'jpg,png,gif,svg,jpeg'])->move(ROOT_PATH . 'public' . DS . 'uploads'); // 文件目录
		        if($info){
		            $data['cover_pic'] = '/uploads/'.$info->getSaveName(); // 文件路径
		        }else{
		        	return returnJson(400, $file->getError());
		        }
		    } else {
		    	return returnJson(400, '请上传图片');
		    }
		    unset($info); // 释放资源

		    // 处理参会人员
			$data['intro']		=	htmlentities($param['intro']);
			$joinUidAll = explode(",", $param['join_uid_all']);
			$joinUidMust = explode(",", $param['join_uid_must']);
			// 根据员工工号查出员工ID
			$uid = Db::name('ims_member')->where('staff_number','in',$joinUidAll)->column('staff_number, id');
			// 全部参会人员
			$join = array();
			foreach ( $joinUidAll as $k => $v ) {
				// 数据不同步，及时请求保存
				if ( !isset($uid[$v]) || $uid[$v] == '' || $uid[$v] == null ) {
					// 获取员工资料
					$uid[$v] = $this->userInfoOne($v);
				}
				if ( in_array($v, $joinUidMust) ) {
					$join[$k]['is_must'] = 1; // 必须参会人员
				} else {
					$join[$k]['is_must'] = 0;
				}
				$join[$k]['join_id'] = $uid[$v];
			}
			$data['join'] = $join;
			$data['is_vm'] =2;

			// 实例model添加数据
			$meetingModel = new ImsMeetingLiveModel();
			$res = $meetingModel->set($data);
			
			$this->traceLog('请求了[发起会议]接口'); // 操作日志
			if ( $res['code'] == 1 ) {
				return returnJson(200, '会议发起成功');
			} else {
				$this->delFile('./uploads/', '.'.$data['cover_pic']);// 删除文件
				return returnJson(400, '会议发起失败');
			}
		} else {
			return returnJson(400, 'false');

		}
	}

	/**
	 * 发起会议前数据请求接口
	 */
	public function meetingResource()
	{
		$param = request()->param(); // 获取用户传参
		// 检查登录
		if ( !isset($param['token_key']) || empty($param['token_key'])) {
			return returnJson(400, 'token_key不能为空');
		} else {
			$verifyToken = $this->verifyToken($param['token_key']);
			if ( $verifyToken != '1111') return $verifyToken;
		}

		// 获取会议地址
		$addressModel = new ImsAddressModel();
		$address = $addressModel->lists(['status'=>1], '', 'is_default desc');

		// 获取会议分类
		$categoryModel = new PortalCategoryModel();
		$category = $categoryModel->categoryTree(2,1,'id,name');

		$data['address'] = $address;
		$data['category'] = $category;

		$this->traceLog('请求了[发起会议前参数请求]接口'); // 操作日志
		return returnJson(200, '', $data);
	}
}
